<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索" prop="username">
              <el-input placeholder="订单编号、报名人名称、报名人手机号、快递/物流单号" v-model="queryParams.search" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态" prop="activity_order_status">
              <el-select v-model="queryParams.activity_order_status" placeholder="请选择订单状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="tableData" border class="table">
        <el-table-column prop="activity_order_id" label="ID" width="80" fixed />
        <el-table-column prop="activity_order_sn" label="订单编号" width="240" fixed />
        <el-table-column prop="sign_up_name" label="报名人名称" />
        <el-table-column label="报名人手机号">
          <template #default="scope">
            {{ encryptPhone(scope.row.sign_up_phone) }}
          </template>
        </el-table-column>
        <el-table-column prop="province_name" label="省名称" />
        <el-table-column prop="city_name" label="市名称" />
        <el-table-column prop="area_name" label="区名称" />
        <el-table-column prop="total_activity_price" label="订单金额" />
        <el-table-column prop="pay_at" label="支付时间" />
        <el-table-column prop="activity_order_status" label="订单状态">
          <template #default="scope">
            {{ formatStatus(scope.row.activity_order_status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button link @click="handleView(scope.row)">查看</el-button>
            <template v-if="scope.row.activity_order_status === -1">
              <el-button link type="success" @click="handleApproveRefund(scope.row)">通过</el-button>
              <el-button link type="danger" @click="handleRejectRefund(scope.row)">拒绝</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </el-card>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="订单详情" width="800">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单ID">{{ currentRow.activity_order_id }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{ currentRow.activity_order_sn }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentRow.sign_up_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ encryptPhone(currentRow.sign_up_phone) }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">{{ currentRow.total_activity_price }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ formatStatus(currentRow.activity_order_status) }}</el-descriptions-item>
        <el-descriptions-item label="拒绝原因">{{ currentRow.reason_rejection }}</el-descriptions-item>
        <el-descriptions-item label="申请退款原因">{{ currentRow.refund_reason }}</el-descriptions-item>
        <el-descriptions-item label="活动封面图">
          <img :src="currentRow.activity_cover_path" alt="活动封面图"
            style="max-width: 300px; max-height: 200px; object-fit: contain;">
        </el-descriptions-item>
        <el-descriptions-item label="小活动">
          <div>
            <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ebeef5; border-radius: 4px;">
              <p><strong>日期：</strong>{{ currentRow.activity_spec_data.activity_at }}</p>
              <p><strong>时间：</strong>{{ currentRow.activity_spec_data.activity_start_at }} - {{
                currentRow.activity_spec_data.activity_end_at }}</p>
              <p><strong>价格：</strong>¥{{ currentRow.activity_spec_data.activity_price }}</p>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 拒绝退款对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝退款" width="500">
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="订单编号">
          <el-input v-model="rejectForm.orderSn" disabled />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="rejectForm.totalPrice" disabled />
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reason">
          <el-input v-model="rejectForm.reason" type="textarea" placeholder="请输入拒绝退款的原因" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </template>
    </el-dialog>

    <!-- 通过退款对话框 -->
    <el-dialog v-model="approveDialogVisible" title="通过退款" width="500">
      <el-form :model="approveForm" :rules="approveRules" ref="approveFormRef" label-width="100px">
        <el-form-item label="订单编号">
          <el-input v-model="approveForm.orderSn" disabled />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number v-model="approveForm.refundAmount" :min="0.01" :max="approveForm.maxAmount" :precision="2"
            :controls="false" />
          <span class="max-amount-tip">最大可退款金额: ¥{{ approveForm.maxAmount }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";

export default {
  name: "UserList",
  mixins: [tableMixin],
  data() {
    return {
      companyChildList: {},
      //查询参数
      queryParams: {
        search: '',
        activity_order_status: null
      },
      apimodel: "activityjifengood",
      apival: "orderList",
      // 状态选项
      statusOptions: [
        { value: -66, label: "全部" },
        { value: 0, label: "待支付" },
        { value: 10, label: "已支付" },
        { value: -1, label: "申请退款" },
        { value: -2, label: "拒绝退款" },
        { value: -10, label: "已退款" }
      ],
      viewDialogVisible: false,
      rejectDialogVisible: false,
      approveDialogVisible: false,
      currentRow: {},
      rejectForm: {
        orderSn: '',
        totalPrice: '',
        reason: ''
      },
      approveForm: {
        orderSn: '',
        refundAmount: 0,
        maxAmount: 0,
        orderId: null
      },
      approveRules: {
        refundAmount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '退款金额不能小于0.01', trigger: 'blur' }
        ]
      },
      form: {
        image_url: "",
        link_url: "",
        banner_title: "",
        sort_order: 0,
      },
      rules: {},
      companys: [],
      classlist: [],
      orderInfo: {},
    };
  },
  mounted() {
    api.classaa.getList({ size: 999 }).then((res) => {
      if (res.data.code == 200) {
        this.classlist = res.data.content.data;
      }
    });
  },
  methods: {
    // 手机号加密
    encryptPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
    },

    // 格式化状态显示
    formatStatus(status) {
      const item = this.statusOptions.find(item => item.value === status);
      return item ? item.label : status;
    },

    // 查看订单详情
    handleView(row) {
      this.currentRow = row;
      this.viewDialogVisible = true;
    },

    // 处理拒绝退款
    handleRejectRefund(row) {
      this.rejectForm = {
        orderSn: row.activity_order_sn,
        totalPrice: row.total_activity_price,
        reason: '',
        orderId: row.activity_order_id
      };
      this.rejectDialogVisible = true;
    },

    // 确认拒绝退款
    confirmReject() {
      if (!this.rejectForm.reason) {
        this.$message.warning('请输入拒绝原因');
        return;
      }

      // 这里调用API拒绝退款
      console.log('拒绝退款', this.rejectForm);
      // 示例API调用:
      api.activityjifengood.rejectRefund({
        activity_order_sn: this.rejectForm.orderSn,
        reason_rejection: this.rejectForm.reason,
        activity_order_status: -2,
        refund_total: this.rejectForm.totalPrice
      }).then(res => {
        if (res?.status == 200) {
          this.rejectDialogVisible = false;
          this.$message.success("已成功拒绝退款");
          this.getTableData();
        }
      });
    },

    // 处理通过退款
    handleApproveRefund(row) {
      console.log(row)
      this.approveForm = {
        orderSn: row.activity_order_sn,
        refundAmount: row.total_activity_price,
        maxAmount: row.total_activity_price,
        orderId: row.activity_order_id
      };
      this.approveDialogVisible = true;
    },

    // 确认通过退款
    confirmApprove() {
      if (this.approveForm.refundAmount < 0.01 || this.approveForm.refundAmount > this.approveForm.maxAmount) {
            this.$message.warning('退款金额必须在0.01和订单总金额之间');
            return;
          }
          console.log(this.rejectForm,'111')
          // 示例API调用:
          api.activityjifengood.rejectRefund({
            activity_order_sn: this.approveForm.orderSn,
            reason_rejection: '',
            activity_order_status: -10,
            refund_total: this.approveForm.refundAmount
          }).then(res => {
            this.$message.success('操作成功');
            this.approveDialogVisible = false;
            this.getTableData();
          });
    },

    // 订单发货
    handleDelivery(row) {
      this.currentRow = row;
      this.deliveryForm.tracking_sn = row.tracking_sn;
      this.deliveryDialogVisible = true;
    },

    // 加载公司数据
    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        tag_name: "",
        is_type: "",
      };
      this.resetForm();
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.banner
            .del({
              tag_id: row.tag_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => { });
    },

    resetForm() {
      this.$refs.formRef.resetFields();
    },

    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.max-amount-tip {
  margin-left: 10px;
  color: #888;
  font-size: 12px;
}
</style>